package dao;

import controller.AdminRecordServlet;
import model.BookRecord;
import model.MemberUser;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;

public class BookRecordDao {
    public static final Logger logger = LogManager.getLogger(BookRecordDao.class);
    String record_table = "book_record";
    Database database = new Database();

    public boolean borrowBook(int bookId, int userId, Date borrowDate) {
        if (bookId == 0 || userId == 0 || borrowDate == null) {
            logger.warn("borrowBook insert date is null");
            return false;
        } else {
            try {
                // TODO:重复借书检查
                String borrowBook = "insert into " + record_table + " (bookId,userId,rentDate) values(?,?,?)";
                PreparedStatement preparedStatement = database.getPreparedStatement(borrowBook);
                preparedStatement.setInt(1, bookId);
                preparedStatement.setInt(2, userId);
                preparedStatement.setDate(3, new java.sql.Date(borrowDate.getTime()));
                logger.info("borrowBook SQL:" + preparedStatement);
                preparedStatement.executeUpdate();
                logger.info("borrowBook success by booId:" + bookId + " userId:" + userId + " rentDate:" + borrowDate);
                return true;
            } catch (SQLException e) {
                logger.error("borrowBook Error:" + e);
                throw new RuntimeException(e);
            }
        }
    }

    public boolean backBook(Date backDate, int id) {
        if (backDate == null || id == 0) {
            logger.warn("backBook update date is null");
            return false;
        } else {
            try {
                // TODO:重复还书检查
                String backBook = "update " + record_table + " set backDate = ? where id = ?";
                PreparedStatement preparedStatement = database.getPreparedStatement(backBook);
                preparedStatement.setDate(1, new java.sql.Date(backDate.getTime()));
                preparedStatement.setInt(2, id);
                logger.info("backBook SQL:" + preparedStatement);
                preparedStatement.executeUpdate();
                logger.info("backBook success with backDate:" + backDate + " id:" + id);
                return true;
            } catch (SQLException e) {
                logger.error("backBook Error:" + e);
                throw new RuntimeException(e);
            }
        }
    }

    /**
     * 获取借阅记录
     *
     * @param userId 传入用户ID
     * @return 返回借阅记录
     * @throws SQLException SQL Error
     */
    public ArrayList<BookRecord> getUserRecordList(int userId) throws SQLException {
        String getRecord = "select book_record.id,bookId,userId,rentDate,backDate,book.name from book_record join book on bookId = book.id where userId = " + userId;
        logger.info("getUserRecordList SQL:" + getRecord);
        return getBookRecords(getRecord);
    }

    /**
     * 获取所有用户借阅记录
     *
     * @return 所有用户借阅记录数组对象
     * @throws SQLException SQL Error
     */
    public ArrayList<BookRecord> getAllRecordList() throws SQLException {
        String getRecord = "select book_record.id,bookId,userId,rentDate,backDate,book.name from book_record join book on bookId = book.id";
        logger.info("getAllRecordList SQL:" + getRecord);
        return getBookRecords(getRecord);
    }

    /**
     * 获取用户借阅记录总方法，这个方法不要外部使用
     *
     * @param getRecord SQL语句
     * @return 借阅记录数组对象
     */
    private ArrayList<BookRecord> getBookRecords(String getRecord) {
        ArrayList<BookRecord> recordList = new ArrayList<>();
        try {
            try (ResultSet resultSet = database.query(getRecord)) {
                while (resultSet.next()) {
                    BookRecord bookRecord = new BookRecord();
                    bookRecord.setId(resultSet.getInt("id"));
                    bookRecord.setUserId(resultSet.getInt("userId"));
                    bookRecord.setBookId(resultSet.getInt("bookId"));
                    bookRecord.setRentDate(resultSet.getDate("rentDate"));
                    bookRecord.setBackDate(resultSet.getDate("backDate"));
                    bookRecord.setBookName(resultSet.getString("name"));
                    recordList.add(bookRecord);
                    logger.info("getBookRecords date:" + recordList);
                }
            }
        } catch (SQLException e) {
            logger.error("getBookRecords Error:" + e);
            throw new RuntimeException(e);
        }
        return recordList;
    }

}
